<?php

class Application_Model_Mapper_BildMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Bild');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_BildUpload $bild)
	{		
			$now = new DateTime();
		/**
		 * Fill data array
		 */
		$data = array(
				'id' => $bild->getId(),
				'name' => $bild->getName(),
				'beschreibung' => $bild->getBeschreibung(),
				'kategorie' => $bild->getKategorie(),
				'referenzId' => $bild->getReferenzId(),
				'referenzObjekt' => $bild->getReferenzObjekt(),
				'created' => date('Y-m-d H:i:s'),
		);

		return $this->getDbTable()->insert($data);
	}


	public function delete ($id)
	{
		$data = array(
				'deleted' => true);
		return $this->getDbTable()->update($data, array(
				'id = ?' => $id));
	}

	public function fetchID($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('bild');
		$entry->where('bild.id = ?', $id);
		return $entry->query()->fetch();
	}

	public function fetchBeschreibung($beschreibung)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('bild');
		$entry->where('bild.beschreibung = ?', $beschreibung);
		return $entry->query()->fetch();
	}

	public function fetchAll()
	{
 		$db = Zend_Db_Table::getDefaultAdapter();
 		$entry = new Zend_Db_Select($db);
		$entry->from('bild');
		return $entry->query()->fetchall();
	}

	public function fetchUserbilder($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('bild');
		$entry->where('bild.referenzId = ?', $id);
		$entry->where('bild.referenzObjekt = user');
		return $entry->query()->fetch();
	}

	public function fetchKategorie($kategorie)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('bild');
		$entry->where('bild.kategorie = ?', $kategorie);
		return $entry->query()->fetch();
	}
}